"use strict";
//app.js
const api = require("./utils/api.js")
const time = require('./utils/time.js')
const request = require('./utils/request.js')
const meetings = require('./utils/meetings.js')


App({
  api: api,
  time: time,
  meetings: meetings,
	onLaunch: function () {
		//调用API从本地缓存中获取数据
		var logs = wx.getStorageSync('logs') || []
		logs.unshift(Date.now())
		wx.setStorageSync('logs', logs)
	},
	getUserInfo:function(cb){
    var that = this
    return new Promise((resolve, reject) => {
      console.log("app.getUserInfo:"+this.globalData.userInfo);
      console.log(this.globalData.userInfo);
      if (this.globalData.userInfo && this.globalData.userInfo.id ) {
        resolve(this.globalData.userInfo)
      } else {
        this.login(that,cb)
      }
    })
	},
	globalData:{
    config: null,
    userInfo: null,//id nickname open_paper is_superuser userid
    getUserInfoing: false,
    getUserInfoPromise: [],
    time_difference: 0,
    classtyps:[],
  },
  nowDate: function(){
    return new Date(new Date().getTime() + this.globalData.timeDifference)
  },
  config: function(){
    return new Promise((resolve, reject) => {
      if (this.globalData.config != null){
        resolve(this.globalData.config)
        return
      }
      api.api_meeting_config().then(res => {
        this.globalData.config = res
        resolve(this.globalData.config)
      }).catch(res => {
        reject(res)
      })
    })
  },
  gotoHome: function(){
    wx.reLaunch({
      // url: '/pages/room/list',
      url: '/pages/user/welcome',
    })
  },
  login:function(that, cb) {
    console.log("login()--begin")
    return new Promise(function(resolve){
      // 显示加载中
      wx.showToast({
        title: "loading",
        icon: 'loading'
      });
      wx.login({
        success: function (res) {
          console.log("wx.login -success");
          resolve(res);
        },
        fail:function(){
          console.log("wx.login -fail");
        }
      });
    }).then(function (xdata){
      return new Promise(function(resolve, reject){
        wx.request({
          url: api.serverapp+'/wxa/user/login',
          data: {
            code: xdata.code
          },
          success: function(res) {
            var data = res.data;
            console.log("/wxa/user/login-success:"+res)
            console.log(res)
            request.setCookieByHead(res.header);
            if (data.errcode !== 500) {
              wx.setStorageSync("sessionId", data.sessionId);
              resolve(res);
            } else {
              reject(data);
            }
          }
        })
      });
    }).then(function (xdata){
      return new Promise(function(resolve, reject){
        wx.getUserInfo({
          success: function (res) {
            console.log("wx.getUserInfo:"+res);
            console.log(res);
            // that.globalData.userInfo = res.userInfo
            resolve(res);
          }, 
          fail: function (res) {
            // 取消授权
            reject(res);
          }
        })
      });
    }, function(xdata){
      wx.showModal({
        title: '提示',
        content: xdata.errmsg,
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      });
    }).then(function (xdata){
      return new Promise(function(resolve, reject){
        wx.request({
          url: api.serverapp+'/wxa/user/info',
          data: {
            rawData: xdata.rawData,
            signature: xdata.signature,
            encryptedData: xdata.encryptedData,
            iv: xdata.iv
          },
          header: {
            'wxa-sessionid': wx.getStorageSync("sessionId")
          },
          success: function(res) {
            console.log("/wxa/user/info:"+res);
            console.log(res);
            getApp().globalData.userInfo = res.data
            resolve(res);
          }
        })
      });
    }, function(xdata){
      wx.hideToast();
      wx.showModal({
        title: '提示',
        content: "您取消了授权",
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      });
    }).then(function(xdata){
      wx.hideToast();
      typeof cb == "function" && cb(that.globalData.userInfo);
    }, function(xdata){
      wx.hideToast();
      wx.showModal({
        title: '提示',
        content: xdata.errmsg,
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      });
    });
  }
})


/*
App({
  api: api,
  time: time,
  meetings: meetings,
  onLaunch: function (options) {
    // 获取用户信息
    this.userInfo()
  },
  onShow: function(options){
  },
  onHide: function (options) {
  },
  globalData: {
    config: null,
    userInfo: null,
    getUserInfoing: false,
    getUserInfoPromise: [],
    time_difference: 0,
    classtyps:[],
  },
  nowDate: function(){
    return new Date(new Date().getTime() + this.globalData.timeDifference)
  },
  config: function(){
    return new Promise((resolve, reject) => {
      if (this.globalData.config != null){
        resolve(this.globalData.config)
        return
      }
      api.api_meeting_config().then(res => {
        this.globalData.config = res
        resolve(this.globalData.config)
      }).catch(res => {
        reject(res)
      })
    })
  },
  userInfo: function () {
    return new Promise((resolve, reject) => {
      this.globalData.getUserInfoPromise.push([resolve, reject])
      if (this.globalData.getUserInfoing) {
        return
      }
      this.globalData.getUserInfoing = true
      let callback = (index, info) => {
        this.globalData.getUserInfoing = false
        while (this.globalData.getUserInfoPromise.length > 0) {
          let pro = this.globalData.getUserInfoPromise.pop()
          pro[index](info);
        }
        if (index == 0 && info.need_refresh){
          this.getUserInfo()
        }
      }
      if (this.globalData.userInfo != null) {
        callback(0, this.globalData.userInfo)
        return
      }
      api.api_wechat_user_info().then(data => {
        if (!data.avatarurl){
          this.getUserInfo().then(res => {
            callback(0, res)
          }).catch(res => {
            callback(1, res)
          })
        }else{
          this.globalData.userInfo = data
          callback(0, this.globalData.userInfo)
        }
      }).catch(res => {
        callback(1, res)
      })
    })
  },
  getUserInfo: function () {
    console.log("getUserInfo");
    return new Promise((resolve, reject) => {
      this.login().then(res => {
        wx.getUserInfo({
          withCredentials: true,
          lang: 'zh_CN',
          success: res => {
            console.log("wx.getUserInfo.iv"+res.iv);
            this.updateUserInfo(res.encryptedData, res.iv).then(res => {
              resolve(res)
            }).catch(res => {
              reject(res)
            })

          },
          fail(res) {
            reject(res.errMsg);
          }
        })
      })
    })
  },
  updateUserInfo: function (encryptedData, iv){
    
    console.log("updateUserInfo")
    return new Promise((resolve, reject) => {
      api.api_wechat_user_info({ encrypted_data: encryptedData, iv: iv }).then(data => {
        this.globalData.userInfo = data
        resolve(this.globalData.userInfo)
      }).catch(msg => {
        this.login().then(res => {
          reject(msg)
        })
      })
    })
  },
  onGetPhoneNumber: function (e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      return this.updateUserInfo(e.detail.encryptedData, e.detail.iv)
    }else{
      return new Promise((resolve, reject) => { reject("获取失败") });
    }
  },

  onGetUserInfo: function (e) {
    console.log("onGetUserInfo")
    if (e.detail.errMsg == 'getUserInfo:ok') {
      return this.updateUserInfo(e.detail.encryptedData, e.detail.iv)
    } else {
      return new Promise((resolve, reject) => { reject("获取失败") });
    }
  },
  gotoHome: function(){
    wx.reLaunch({
      // url: '/pages/room/list',
      url: '/pages/user/welcome',
    })
  },
  login: function() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: res => {
          console.log("wx.login:"+res.code);
          api.api_wechat_login({js_code: res.code}).then(data => {
            resolve(data)
          })
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
        },
        fail: res => {
          reject(res)
        }
      })
    })
  }
})
*/